/**
 * WMS业务状态管理模块
 *
 * 管理WMS系统的基础数据，包括仓库、库区、商户、商品分类、商品品牌等
 * 提供统一的数据获取、缓存和状态管理功能
 */
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { WmsBasicService } from "@/api/wms/basicApi";

/**
 * WMS状态管理Store
 */
export const useWmsStore = defineStore(
  "wms",
  () => {
    // ==================== 仓库管理 ====================

    /**
     * 仓库列表
     */
    const warehouseList = ref<WMS.Basic.WarehouseInfo[]>([]);

    /**
     * 仓库映射表（计算属性）
     * 用于快速根据ID查找仓库信息
     */
    const warehouseMap = computed(() => {
      const map = new Map<number, WMS.Basic.WarehouseInfo>();
      warehouseList.value.forEach((warehouse) => {
        map.set(warehouse.id, warehouse);
      });
      return map;
    });

    /**
     * 获取仓库列表
     */
    const getWarehouseList = async () => {
      try {
        const response = await WmsBasicService.getAllWarehouses();
        warehouseList.value = response || [];
      } catch (error) {
        console.error("获取仓库列表失败:", error);
        warehouseList.value = [];
      }
    };

    /**
     * 根据ID获取仓库信息
     */
    const getWarehouseById = (
      id: number,
    ): WMS.Basic.WarehouseInfo | undefined => {
      return warehouseMap.value.get(id);
    };

    /**
     * 获取启用状态的仓库列表
     */
    const getActiveWarehouses = computed(() => {
      return warehouseList.value.filter((warehouse) => warehouse.status === 1);
    });

    // ==================== 库区管理 ====================

    /**
     * 库区列表
     */
    const areaList = ref<WMS.Basic.AreaInfo[]>([]);

    /**
     * 库区映射表（计算属性）
     */
    const areaMap = computed(() => {
      const map = new Map<number, WMS.Basic.AreaInfo>();
      areaList.value.forEach((area) => {
        map.set(area.id, area);
      });
      return map;
    });

    /**
     * 按仓库分组的库区映射表（计算属性）
     */
    const areasByWarehouse = computed(() => {
      const map = new Map<number, WMS.Basic.AreaInfo[]>();
      areaList.value.forEach((area) => {
        if (!map.has(area.warehouseId)) {
          map.set(area.warehouseId, []);
        }
        map.get(area.warehouseId)!.push(area);
      });
      return map;
    });

    /**
     * 获取库区列表
     */
    const getAreaList = async () => {
      try {
        const response = await WmsBasicService.getAllAreas();
        areaList.value = response || [];
      } catch (error) {
        console.error("获取库区列表失败:", error);
        areaList.value = [];
      }
    };

    /**
     * 根据ID获取库区信息
     */
    const getAreaById = (id: number): WMS.Basic.AreaInfo | undefined => {
      return areaMap.value.get(id);
    };

    /**
     * 根据仓库ID获取库区列表
     */
    const getAreasByWarehouseId = (
      warehouseId: number,
    ): WMS.Basic.AreaInfo[] => {
      return areasByWarehouse.value.get(warehouseId) || [];
    };

    /**
     * 获取启用状态的库区列表
     */
    const getActiveAreas = computed(() => {
      return areaList.value.filter((area) => area.status === 1);
    });

    // ==================== 商户管理 ====================

    /**
     * 商户列表
     */
    const merchantList = ref<WMS.Basic.MerchantInfo[]>([]);

    /**
     * 商户映射表（计算属性）
     */
    const merchantMap = computed(() => {
      const map = new Map<number, WMS.Basic.MerchantInfo>();
      merchantList.value.forEach((merchant) => {
        map.set(merchant.id, merchant);
      });
      return map;
    });

    /**
     * 获取商户列表
     */
    const getMerchantList = async () => {
      try {
        const response = await WmsBasicService.getAllMerchants();
        merchantList.value = response || [];
      } catch (error) {
        console.error("获取商户列表失败:", error);
        merchantList.value = [];
      }
    };

    /**
     * 根据ID获取商户信息
     */
    const getMerchantById = (
      id: number,
    ): WMS.Basic.MerchantInfo | undefined => {
      return merchantMap.value.get(id);
    };

    /**
     * 获取启用状态的商户列表
     */
    const getActiveMerchants = computed(() => {
      return merchantList.value.filter((merchant) => merchant.status === 1);
    });

    // ==================== 商品分类管理 ====================

    /**
     * 商品分类列表
     */
    const itemCategoryList = ref<WMS.Basic.ItemCategoryInfo[]>([]);

    /**
     * 商品分类树形列表
     */
    const itemCategoryTreeList = ref<WMS.Basic.ItemCategoryTreeInfo[]>([]);

    /**
     * 商品分类映射表（计算属性）
     */
    const itemCategoryMap = computed(() => {
      const map = new Map<number, WMS.Basic.ItemCategoryInfo>();
      itemCategoryList.value.forEach((category) => {
        map.set(category.id, category);
      });
      return map;
    });

    /**
     * 获取商品分类列表
     */
    const getItemCategoryList = async () => {
      try {
        const response = await WmsBasicService.getAllItemCategories();
        itemCategoryList.value = response || [];
      } catch (error) {
        console.error("获取商品分类列表失败:", error);
        itemCategoryList.value = [];
      }
    };

    /**
     * 获取商品分类树形列表
     */
    const getItemCategoryTreeList = async () => {
      try {
        const response = await WmsBasicService.getItemCategoryTree();
        itemCategoryTreeList.value = response || [];
      } catch (error) {
        console.error("获取商品分类树形列表失败:", error);
        itemCategoryTreeList.value = [];
      }
    };

    /**
     * 根据ID获取商品分类信息
     */
    const getItemCategoryById = (
      id: number,
    ): WMS.Basic.ItemCategoryInfo | undefined => {
      return itemCategoryMap.value.get(id);
    };

    /**
     * 获取启用状态的商品分类列表
     */
    const getActiveItemCategories = computed(() => {
      return itemCategoryList.value.filter((category) => category.status === 1);
    });

    // ==================== 商品品牌管理 ====================

    /**
     * 商品品牌列表
     */
    const itemBrandList = ref<WMS.Basic.ItemBrandInfo[]>([]);

    /**
     * 商品品牌映射表（计算属性）
     */
    const itemBrandMap = computed(() => {
      const map = new Map<number, WMS.Basic.ItemBrandInfo>();
      itemBrandList.value.forEach((brand) => {
        map.set(brand.id, brand);
      });
      return map;
    });

    /**
     * 获取商品品牌列表
     */
    const getItemBrandList = async () => {
      try {
        const response = await WmsBasicService.getAllItemBrands();
        itemBrandList.value = response || [];
      } catch (error) {
        console.error("获取商品品牌列表失败:", error);
        itemBrandList.value = [];
      }
    };

    /**
     * 根据ID获取商品品牌信息
     */
    const getItemBrandById = (
      id: number,
    ): WMS.Basic.ItemBrandInfo | undefined => {
      return itemBrandMap.value.get(id);
    };

    /**
     * 获取启用状态的商品品牌列表
     */
    const getActiveItemBrands = computed(() => {
      return itemBrandList.value.filter((brand) => brand.status === 1);
    });

    // ==================== 统一初始化方法 ====================

    /**
     * 初始化所有基础数据
     */
    const initAllBasicData = async () => {
      await Promise.all([
        getWarehouseList(),
        getAreaList(),
        getMerchantList(),
        getItemCategoryList(),
        getItemCategoryTreeList(),
        getItemBrandList(),
      ]);
    };

    /**
     * 刷新指定类型的基础数据
     */
    const refreshBasicData = async (
      type: "warehouse" | "area" | "merchant" | "category" | "brand" | "all",
    ) => {
      switch (type) {
        case "warehouse":
          await getWarehouseList();
          break;
        case "area":
          await getAreaList();
          break;
        case "merchant":
          await getMerchantList();
          break;
        case "category":
          await getItemCategoryList();
          await getItemCategoryTreeList();
          break;
        case "brand":
          await getItemBrandList();
          break;
        case "all":
          await initAllBasicData();
          break;
      }
    };

    // ==================== 返回状态和方法 ====================

    return {
      // 仓库管理
      warehouseList,
      warehouseMap,
      getWarehouseList,
      getWarehouseById,
      getActiveWarehouses,

      // 库区管理
      areaList,
      areaMap,
      areasByWarehouse,
      getAreaList,
      getAreaById,
      getAreasByWarehouseId,
      getActiveAreas,

      // 商户管理
      merchantList,
      merchantMap,
      getMerchantList,
      getMerchantById,
      getActiveMerchants,

      // 商品分类管理
      itemCategoryList,
      itemCategoryTreeList,
      itemCategoryMap,
      getItemCategoryList,
      getItemCategoryTreeList,
      getItemCategoryById,
      getActiveItemCategories,

      // 商品品牌管理
      itemBrandList,
      itemBrandMap,
      getItemBrandList,
      getItemBrandById,
      getActiveItemBrands,

      // 统一管理方法
      initAllBasicData,
      refreshBasicData,
    };
  },
  {
    // 配置状态持久化
    persist: true,
  },
);
